package club.xiaojiawei.linkedlist;

/**
 * @author 肖嘉威
 * @version 1.0
 * @date 2022/4/21 22:49
 * @question 203.移除链表元素
 * @description 给你一个链表的头节点 head 和一个整数 val ，请你删除链表中所有满足 Node.val == val 的节点，并返回 新的头节点 。
 */
public class RemoveLinkedListElement203 {

    public static void main(String[] args) {
        ListNode head = new ListNode(5);
        ListNode temp =head;

        temp = temp.next = new ListNode(1);
//        temp = temp.next = new ListNode(4);
//        temp = temp.next = new ListNode(5);
//        temp = temp.next = new ListNode(5);
//        temp = temp.next = new ListNode(1);
        ListNode result = removeElements1(head, 5);
        System.out.println(result);
        System.out.println(head);
    }

    public static ListNode removeElements(ListNode head, int val) {
        if (head == null){
            return null;
        }
        ListNode temp = head;
        while (temp.next != null){
            if (temp.next.val == val){
                temp.next = temp.next.next;
            }else {
                temp = temp.next;
            }
        }

        if (head.val == val){
            if (head.next == null){
                return null;
            }else {
                return head.next;
            }
        }
        return head;
    }

    public static ListNode removeElements1(ListNode head, int val) {
        ListNode dummyHead = new ListNode(0);
        dummyHead.next = head;
        ListNode temp = dummyHead;
        while (temp.next != null) {
            if (temp.next.val == val) {
                temp.next = temp.next.next;
            } else {
                temp = temp.next;
            }
        }
        return dummyHead.next;
    }

    static class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }

        @Override
        public String toString() {
            return "ListNode{" +
                    "val=" + val +
                    '}';
        }
    }
}